<script setup>
import { ref, reactive, onMounted } from 'vue'

// 订单状态选项
const orderStatusOptions = [
    { value: '0', label: '待付款' },
    { value: '1', label: '待发货' },
    { value: '2', label: '已发货' },
    { value: '3', label: '已完成' },
    { value: '4', label: '已取消' },
    { value: '5', label: '已退款' }
]

// 支付方式选项
const paymentTypeOptions = [
    { value: 'wechat', label: '微信支付' },
    { value: 'alipay', label: '支付宝' },
    { value: 'balance', label: '余额支付' },
    { value: 'offline', label: '线下支付' }
]

// 搜索条件
const searchForm = reactive({
    orderNo: '',
    status: '',
    dateRange: [],
    paymentType: '',
    userName: ''
})

// 表格数据
const tableData = ref([
    {
        id: '2023071001',
        orderNo: 'DD202307100001',
        userName: '张三',
        userPhone: '13812345678',
        totalAmount: 398.00,
        payAmount: 376.00,
        paymentType: 'wechat',
        status: '1',
        createTime: '2023-07-10 15:30:24',
        payTime: '2023-07-10 15:35:47',
        remark: '请尽快发货，谢谢！',
        address: '北京市朝阳区某某街道100号',
        goodsList: [
            { id: 1, name: '2023新款笔记本电脑轻薄本', image: 'https://via.placeholder.com/60', price: 199.00, quantity: 2, totalPrice: 398.00 }
        ]
    },
    {
        id: '2023071002',
        orderNo: 'DD202307100002',
        userName: '李四',
        userPhone: '13912345678',
        totalAmount: 127.50,
        payAmount: 127.50,
        paymentType: 'alipay',
        status: '2',
        createTime: '2023-07-10 16:12:33',
        payTime: '2023-07-10 16:14:22',
        remark: '',
        address: '上海市浦东新区某某路200号',
        goodsList: [
            { id: 2, name: '男士夏季短袖T恤圆领宽松', image: 'https://via.placeholder.com/60', price: 89.90, quantity: 1, totalPrice: 89.90 },
            { id: 3, name: '水杯保温杯不锈钢', image: 'https://via.placeholder.com/60', price: 37.60, quantity: 1, totalPrice: 37.60 }
        ]
    },
    {
        id: '2023071003',
        orderNo: 'DD202307100003',
        userName: '王五',
        userPhone: '13712345678',
        totalAmount: 1243.00,
        payAmount: 0,
        paymentType: '',
        status: '0',
        createTime: '2023-07-10 16:47:21',
        payTime: '',
        remark: '',
        address: '广州市天河区某某街88号',
        goodsList: [
            { id: 4, name: '北欧简约风格实木床1.8米', image: 'https://via.placeholder.com/60', price: 1243.00, quantity: 1, totalPrice: 1243.00 }
        ]
    },
    {
        id: '2023071004',
        orderNo: 'DD202307100004',
        userName: '赵六',
        userPhone: '13612345678',
        totalAmount: 568.00,
        payAmount: 568.00,
        paymentType: 'wechat',
        status: '3',
        createTime: '2023-07-10 17:10:05',
        payTime: '2023-07-10 17:11:30',
        remark: '',
        address: '深圳市南山区某某路99号',
        goodsList: [
            { id: 5, name: '智能手表多功能运动手环', image: 'https://via.placeholder.com/60', price: 568.00, quantity: 1, totalPrice: 568.00 }
        ]
    },
    {
        id: '2023071005',
        orderNo: 'DD202307100005',
        userName: '钱七',
        userPhone: '13512345678',
        totalAmount: 97.50,
        payAmount: 97.50,
        paymentType: 'balance',
        status: '4',
        createTime: '2023-07-10 17:25:48',
        payTime: '2023-07-10 17:26:10',
        remark: '取消原因：买错了',
        address: '杭州市西湖区某某路55号',
        goodsList: [
            { id: 6, name: '有机新鲜水果礼盒装', image: 'https://via.placeholder.com/60', price: 97.50, quantity: 1, totalPrice: 97.50 }
        ]
    }
])

// 分页配置
const pagination = reactive({
    total: 100,
    currentPage: 1,
    pageSize: 10
})

// 表格加载状态
const tableLoading = ref(false)

// 搜索方法
const handleSearch = () => {
    tableLoading.value = true
    // 这里应该是实际的API调用
    setTimeout(() => {
        tableLoading.value = false
        // 模拟搜索结果
        console.log('搜索条件:', searchForm)
    }, 500)
}

// 重置搜索条件
const resetSearch = () => {
    Object.keys(searchForm).forEach(key => {
        if (key === 'dateRange') {
            searchForm[key] = []
        } else {
            searchForm[key] = ''
        }
    })
    handleSearch()
}

// 处理分页变化
const handleCurrentChange = (val) => {
    pagination.currentPage = val
    handleSearch()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
    pagination.pageSize = val
    pagination.currentPage = 1
    handleSearch()
}

// 获取订单状态对应的标签类型
const getStatusType = (status) => {
    switch (status) {
        case '0': return 'warning'
        case '1': return 'primary'
        case '2': return 'success'
        case '3': return 'info'
        case '4': return 'danger'
        case '5': return 'danger'
        default: return 'info'
    }
}

// 获取订单状态文本
const getStatusText = (status) => {
    return orderStatusOptions.find(item => item.value === status)?.label || '未知状态'
}

// 获取支付方式文本
const getPaymentText = (type) => {
    return paymentTypeOptions.find(item => item.value === type)?.label || '未支付'
}

// 订单详情对话框
const detailDialogVisible = ref(false)
const currentOrder = ref(null)

// 打开订单详情
const openOrderDetail = (order) => {
    currentOrder.value = order
    detailDialogVisible.value = true
}

// 确认发货对话框
const shipDialogVisible = ref(false)
const shipForm = reactive({
    orderNo: '',
    logisticsCompany: '',
    logisticsNo: '',
    remark: ''
})

// 打开发货对话框
const openShipDialog = (order) => {
    shipForm.orderNo = order.orderNo
    shipForm.logisticsCompany = ''
    shipForm.logisticsNo = ''
    shipForm.remark = ''
    shipDialogVisible.value = true
}

// 确认发货
const confirmShipOrder = () => {
    // 这里应该是调用发货API
    console.log('确认发货:', shipForm)
    ElMessage.success('发货成功')
    shipDialogVisible.value = false
    handleSearch() // 刷新列表
}

// 取消订单
const cancelOrder = (orderNo) => {
    ElMessageBox.confirm('确认要取消该订单吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        // 调用取消订单API
        ElMessage.success('订单已取消')
        handleSearch() // 刷新列表
    }).catch(() => { })
}

// 打印订单
const printOrder = (orderNo) => {
    ElMessage.success(`正在打印订单：${orderNo}`)
    // 实现打印逻辑
}

onMounted(() => {
    handleSearch()
})
</script>

<template>
    <div class="order-container">
        <!-- 搜索栏 -->
        <el-card class="search-card">
            <el-form :model="searchForm" label-width="80px" :inline="true" size="default" class="responsive-form">
                <el-form-item label="订单号">
                    <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
                </el-form-item>
                <el-form-item label="订单状态">
                    <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                        <el-option v-for="item in orderStatusOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="支付方式">
                    <el-select v-model="searchForm.paymentType" placeholder="请选择支付方式" clearable>
                        <el-option v-for="item in paymentTypeOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="下单时间" class="date-form-item">
                    <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="客户姓名">
                    <el-input v-model="searchForm.userName" placeholder="请输入客户姓名" clearable />
                </el-form-item>
                <el-form-item class="form-buttons">
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 操作栏 -->
        <div class="action-bar">
            <el-button type="primary" icon="Document">导出订单</el-button>
            <el-button icon="Printer">批量打印</el-button>
        </div>

        <!-- 表格 -->
        <el-card>
            <div class="table-responsive">
                <el-table v-loading="tableLoading" :data="tableData" style="width: 100%" border>
                    <el-table-column prop="orderNo" label="订单号" min-width="180" />
                    <el-table-column label="客户信息" min-width="150">
                        <template #default="scope">
                            <div>{{ scope.row.userName }}</div>
                            <div>{{ scope.row.userPhone }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="订单金额" min-width="150">
                        <template #default="scope">
                            <div>总金额: ￥{{ scope.row.totalAmount.toFixed(2) }}</div>
                            <div v-if="scope.row.payAmount > 0">支付金额: ￥{{ scope.row.payAmount.toFixed(2) }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="支付方式" min-width="120">
                        <template #default="scope">
                            {{ getPaymentText(scope.row.paymentType) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="订单状态" min-width="100">
                        <template #default="scope">
                            <el-tag :type="getStatusType(scope.row.status)">
                                {{ getStatusText(scope.row.status) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="下单时间" min-width="170" />
                    <el-table-column label="操作" min-width="200" fixed="right">
                        <template #default="scope">
                            <div class="action-buttons">
                                <el-button type="text" @click="openOrderDetail(scope.row)">查看详情</el-button>
                                <el-button type="text" @click="printOrder(scope.row.orderNo)">打印</el-button>
                                <el-button v-if="scope.row.status === '1'" type="text"
                                    @click="openShipDialog(scope.row)">发货</el-button>
                                <el-button v-if="scope.row.status === '0'" type="text"
                                    @click="cancelOrder(scope.row.orderNo)">取消</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 订单详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="订单详情" width="90%" max-width="700px" destroy-on-close>
            <template v-if="currentOrder">
                <el-descriptions title="基本信息" :column="2" border>
                    <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
                    <el-descriptions-item label="下单时间">{{ currentOrder.createTime }}</el-descriptions-item>
                    <el-descriptions-item label="订单状态">
                        <el-tag :type="getStatusType(currentOrder.status)">
                            {{ getStatusText(currentOrder.status) }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="支付方式">{{ getPaymentText(currentOrder.paymentType)
                        }}</el-descriptions-item>
                    <el-descriptions-item label="支付时间">{{ currentOrder.payTime || '未支付' }}</el-descriptions-item>
                    <el-descriptions-item label="订单备注">{{ currentOrder.remark || '无' }}</el-descriptions-item>
                </el-descriptions>

                <el-descriptions title="客户信息" :column="1" border class="mt-20">
                    <el-descriptions-item label="客户姓名">{{ currentOrder.userName }}</el-descriptions-item>
                    <el-descriptions-item label="联系电话">{{ currentOrder.userPhone }}</el-descriptions-item>
                    <el-descriptions-item label="收货地址">{{ currentOrder.address }}</el-descriptions-item>
                </el-descriptions>

                <div class="order-goods mt-20">
                    <div class="section-title">商品信息</div>
                    <div class="table-responsive">
                        <el-table :data="currentOrder.goodsList" border>
                            <el-table-column label="商品图片" min-width="100">
                                <template #default="scope">
                                    <el-image :src="scope.row.image" :preview-src-list="[scope.row.image]" fit="cover"
                                        style="width: 60px; height: 60px" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="name" label="商品名称" min-width="200" />
                            <el-table-column prop="price" label="单价" min-width="100">
                                <template #default="scope">
                                    ￥{{ scope.row.price.toFixed(2) }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="quantity" label="数量" min-width="80" />
                            <el-table-column prop="totalPrice" label="小计" min-width="120">
                                <template #default="scope">
                                    ￥{{ scope.row.totalPrice.toFixed(2) }}
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>

                    <div class="order-amount">
                        <div class="amount-item">
                            <span class="label">商品总额：</span>
                            <span class="value">￥{{ currentOrder.totalAmount.toFixed(2) }}</span>
                        </div>
                        <div class="amount-item">
                            <span class="label">实付金额：</span>
                            <span class="value highlight">￥{{ currentOrder.payAmount.toFixed(2) }}</span>
                        </div>
                    </div>
                </div>
            </template>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="detailDialogVisible = false">关闭</el-button>
                    <el-button v-if="currentOrder && currentOrder.status === '1'" type="primary"
                        @click="openShipDialog(currentOrder)">立即发货</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 发货对话框 -->
        <el-dialog v-model="shipDialogVisible" title="订单发货" width="90%" max-width="500px" destroy-on-close>
            <el-form :model="shipForm" label-width="100px">
                <el-form-item label="订单号">
                    <el-input v-model="shipForm.orderNo" disabled />
                </el-form-item>
                <el-form-item label="物流公司" required>
                    <el-select v-model="shipForm.logisticsCompany" placeholder="请选择物流公司" style="width: 100%">
                        <el-option label="顺丰快递" value="SF" />
                        <el-option label="圆通快递" value="YTO" />
                        <el-option label="中通快递" value="ZTO" />
                        <el-option label="申通快递" value="STO" />
                        <el-option label="韵达快递" value="YD" />
                        <el-option label="京东物流" value="JD" />
                    </el-select>
                </el-form-item>
                <el-form-item label="物流单号" required>
                    <el-input v-model="shipForm.logisticsNo" placeholder="请输入物流单号" />
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="shipForm.remark" type="textarea" rows="3" placeholder="备注信息" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="shipDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmShipOrder">确认发货</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.order-container {
    padding: 20px;
    width: 100%;
}

.page-title {
    margin-bottom: 20px;
    font-weight: 500;
    color: #303133;
}

.search-card {
    margin-bottom: 20px;
}

.responsive-form {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.responsive-form .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
}

.date-form-item {
    min-width: 360px;
}

.action-bar {
    margin-bottom: 20px;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.table-responsive {
    width: 100%;
    overflow-x: auto;
}

.action-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.mt-20 {
    margin-top: 20px;
}

.section-title {
    font-weight: bold;
    margin-bottom: 10px;
    padding-left: 8px;
    border-left: 3px solid #409EFF;
}

.order-amount {
    margin-top: 20px;
    text-align: right;
}

.amount-item {
    margin-bottom: 8px;
}

.amount-item .label {
    margin-right: 10px;
}

.amount-item .value {
    font-weight: bold;
}

.amount-item .highlight {
    color: #F56C6C;
    font-size: 18px;
}

@media (max-width: 1200px) {
    .action-bar {
        flex-wrap: wrap;
    }
}

@media (max-width: 768px) {
    .order-container {
        padding: 10px;
    }

    .responsive-form .el-form-item {
        flex-basis: 100%;
    }

    .date-form-item {
        min-width: 100%;
    }

    .form-buttons {
        display: flex;
        justify-content: flex-end;
        width: 100%;
    }

    .pagination-container {
        justify-content: center;
    }

    :deep(.el-pagination__sizes) {
        display: none !important;
    }

    .dialog-footer {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }
}

@media (max-width: 576px) {
    .action-bar {
        flex-direction: column;
        align-items: stretch;
    }

    .action-buttons {
        flex-direction: column;
    }

    :deep(.el-pagination__jump) {
        display: none !important;
    }

    .section-title {
        font-size: 14px;
    }

    .amount-item .label,
    .amount-item .value {
        font-size: 14px;
    }

    .amount-item .highlight {
        font-size: 16px;
    }
}
</style>